package org.jeecg.modules.demo.single.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.analysis.entity.ZnzfTurn;
import org.jeecg.modules.demo.analysis.mapper.ZnzfTurnMapper;
import org.jeecg.modules.demo.applyinfo.entity.ZnzfApply;
import org.jeecg.modules.demo.applyinfo.entity.ZnzfDetermineApart;
import org.jeecg.modules.demo.base.entity.ZnzfEmployee;
import org.jeecg.modules.demo.base.mapper.ZnzfEmployeeMapper;
import org.jeecg.modules.demo.projectroom.entity.ZnzfProject;
import org.jeecg.modules.demo.projectroom.entity.ZnzfRoom;
import org.jeecg.modules.demo.projectroom.mapper.ZnzfProjectMapper;
import org.jeecg.modules.demo.projectroom.mapper.ZnzfRoomMapper;
import org.jeecg.modules.demo.roomapartdistribute.entity.EmployeeCheckedParam;
import org.jeecg.modules.demo.single.entity.ZnzfNeedSingle;
import org.jeecg.modules.demo.single.entity.ZnzfNeedSingleVo;
import org.jeecg.modules.demo.single.mapper.ZnzfNeedSingleMapper;
import org.jeecg.modules.demo.single.service.IZnzfNeedSingleService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.jeecg.modules.system.mapper.SysUserDepartMapper;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.mapper.SysUserRoleMapper;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 单身宿舍申请
 * @Author: jeecg-boot
 * @Date:   2022-03-29
 * @Version: V1.0
 */
@Service
public class ZnzfNeedSingleServiceImpl extends ServiceImpl<ZnzfNeedSingleMapper, ZnzfNeedSingle> implements IZnzfNeedSingleService {

    @Resource
    private SysUserDepartMapper sysUserDepartMapper;

    @Resource
    private ZnzfNeedSingleMapper znzfNeedSingleMapper;

    @Resource
    private ZnzfProjectMapper znzfProjectMapper;

    @Resource
    private ZnzfRoomMapper znzfRoomMapper;

    @Resource
    private ZnzfEmployeeMapper znzfEmployeeMapper;

    @Resource
    private SysUserMapper sysUserMapper;


    @Resource
    private SysUserRoleMapper userRoleMapper;

    @Resource
    private ZnzfTurnMapper turnMapper;

    @Resource
    private SysDepartMapper sysDepartMapper;

    @Override
    public JSONObject applyMessage(String projectId, String uid) {
        JSONObject result = new JSONObject();
        result.put("canApply",false);
        result.put("message","");
        StringBuilder msg = new StringBuilder();
        //TODO 是否满足条件
        //1.查询用户资质，看是否满足条件
        msg.append("当前已满足入住条件。&");
        //3.是否有空房源
        ZnzfProject znzfProject = znzfProjectMapper.selectById(projectId);
        LambdaQueryWrapper<ZnzfRoom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnzfRoom::getProjectId,projectId);
        List<ZnzfRoom> znzfRoomList = znzfRoomMapper.selectList(queryWrapper);
        int tmp = 1;
        int building = znzfRoomList.size();
        int total = 0;
        int people = 0;
        for(ZnzfRoom znzfRoom : znzfRoomList){
            total += znzfRoom.getBedNum();
            people += znzfRoom.getLivedNum();
        }
        if(total > people)
            tmp = 0;
        if(tmp == 1){
            tmp = 0;
            String turnId = znzfProject.getTurnId();
            if(oConvertUtils.isNotEmpty(turnId)){
                String[] turn = turnId.split(";");
                tmp = turn.length;
            }
        }
        msg.append("当前项目共有").append(building).append("套房源，可以入住").append(total).append("人，已入住").append(people).append("人，已轮候").append(tmp).append("人。");

        result.put("canApply",true);
        result.put("message",msg.toString());
        return result;
    }

    @Override
    public List<ZnzfNeedSingleVo> listByOrgCode(Integer step) {
        LambdaQueryWrapper<ZnzfNeedSingle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnzfNeedSingle::getStep,step);
        List<ZnzfNeedSingle> znzfNeedSingleList = znzfNeedSingleMapper.selectList(queryWrapper);
        List<ZnzfNeedSingleVo> znzfNeedSingleVoList = new ArrayList<>();
        for(ZnzfNeedSingle znzfNeedSingle : znzfNeedSingleList){
            ZnzfNeedSingleVo znzfNeedSingleVo = new ZnzfNeedSingleVo();
            ZnzfEmployee znzfEmployee = znzfEmployeeMapper.selectById(znzfNeedSingle.getEid());
            ZnzfProject znzfProject = znzfProjectMapper.selectById(znzfNeedSingle.getProjectId());
            znzfNeedSingleVo.setName(znzfEmployee.getName());
            if(znzfEmployee.getSex() == 1)
                znzfNeedSingleVo.setSex_dicText("男");
            else if(znzfEmployee.getSex() == 0)
                znzfNeedSingleVo.setSex_dicText("女");
            znzfNeedSingleVo.setId(znzfNeedSingle.getId());
            znzfNeedSingleVo.setState(znzfNeedSingle.getCheckState());
            znzfNeedSingleVo.setGro(znzfEmployee.getGro());
            znzfNeedSingleVo.setStation(znzfEmployee.getStation());
            znzfNeedSingleVo.setShop(znzfEmployee.getShop());
            znzfNeedSingleVo.setTel(znzfEmployee.getTel());
            znzfNeedSingleVo.setAge(znzfEmployee.getAge());
            znzfNeedSingleVo.setSeniority(znzfEmployee.getSeniority());
            znzfNeedSingleVo.setIdcard(znzfEmployee.getIdcard());
            znzfNeedSingleVo.setIdcardFront(znzfEmployee.getIdcardFront());
            znzfNeedSingleVo.setIdcardBack(znzfEmployee.getIdcardBack());
            znzfNeedSingleVo.setHousehold(znzfEmployee.getHousehold());
            znzfNeedSingleVo.setAddress(znzfEmployee.getAddress());
            if(znzfEmployee.getIsmarried() == 1)
                znzfNeedSingleVo.setIsmarried_dictText("已结婚");
            else if(znzfEmployee.getIsmarried() == 0)
                znzfNeedSingleVo.setIsmarried_dictText("未结婚");
            znzfNeedSingleVo.setSname(znzfEmployee.getSname());
            znzfNeedSingleVo.setSidcard(znzfEmployee.getSidcard());
            znzfNeedSingleVo.setSworkCompany(znzfEmployee.getSworkCompany());
            znzfNeedSingleVo.setSwordPlace(znzfEmployee.getSwordPlace());
            znzfNeedSingleVo.setShousehold(znzfEmployee.getShousehold());
            znzfNeedSingleVo.setJobName(znzfEmployee.getJobName());
            znzfNeedSingleVo.setJobLevel(znzfEmployee.getJobLevel());
            if(oConvertUtils.isNotEmpty(znzfProject)){
                znzfNeedSingleVo.setProjectId(znzfProject.getId());
                znzfNeedSingleVo.setProjectName(znzfProject.getName());
            }
            znzfNeedSingleVoList.add(znzfNeedSingleVo);
        }
        return znzfNeedSingleVoList;
    }

    @Override
    public int distribute(String eid, String projectId) {
        LambdaQueryWrapper<ZnzfRoom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnzfRoom::getProjectId,projectId);
        List<ZnzfRoom> znzfRoomList = znzfRoomMapper.selectList(queryWrapper);
        for(ZnzfRoom znzfRoom : znzfRoomList){
            if(znzfRoom.getBedNum() > znzfRoom.getLivedNum()){
                znzfRoom.setLivedNum(znzfRoom.getLivedNum() + 1);
                znzfRoomMapper.updateById(znzfRoom);
                ZnzfEmployee znzfEmployee = znzfEmployeeMapper.selectById(eid);
                znzfEmployee.setRoomId(znzfRoom.getId());
                return znzfEmployeeMapper.updateById(znzfEmployee);
            }
        }
        ZnzfProject znzfProject = znzfProjectMapper.selectById(projectId);
        if(oConvertUtils.isEmpty(znzfProject.getTurnId()))
            znzfProject.setTurnId(eid);
        else{
            String tmp = znzfProject.getTurnId();
            tmp = tmp + ";" + eid;
            znzfProject.setTurnId(tmp);
        }
        //往znzf_turn插条数据,用于轮候数据分析
        ZnzfTurn entity = new ZnzfTurn();
        entity.setEid(eid);
        entity.setProjectid(projectId);
        ZnzfEmployee znzfEmployee = znzfEmployeeMapper.selectById(eid);
        entity.setSex(znzfEmployee.getSex());
        ZnzfProject znzfProject1 = znzfProjectMapper.selectById(projectId);
        entity.setType(znzfProject1.getType());
        entity.setProjectName(znzfProject1.getName());
        LambdaQueryWrapper<ZnzfTurn> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(ZnzfTurn::getProjectid, projectId);
        int count = turnMapper.selectCount(queryWrapper1);
        entity.setRank(count + 1);
        SysUser sysUser = sysUserMapper.selectById(znzfEmployee.getUserId());
        entity.setPhone(sysUser.getPhone());
        entity.setDepartName(sysDepartMapper.selectById(sysUser.getDepartIds()).getDepartName());
        entity.setName(znzfEmployee.getName());
        turnMapper.insert(entity);
        return znzfProjectMapper.updateById(znzfProject);
    }

    /**
     * 职工单位科室审核	1
     * 管理单位科室审核	2
     * 管理单位领导审核	3
     * 管理单位公寓车间审核	4
     *
     * @param value
     * @return
     */
    @Override
    public String intToRolename(int value) {
        switch (value){
            case 1: return "check_single_apply_1";
            case 2: return "check_single_apply_2";
            case 3: return "check_single_apply_3";
            case 4: return "check_single_apply_4";
        }
        return "";
    }

    /**
     * 职工单位科室审核	1
     * 管理单位科室审核	2
     * 管理单位领导审核	3
     * 管理单位公寓车间审核	4
     *
     * @param rolename
     * @return
     */
    @Override
    public int roleNameToInt(String rolename) {
        switch (rolename){
            case "check_single_apply_1": return 1;
            case "check_single_apply_2": return 2;
            case "check_single_apply_3": return 3;
            case "check_single_apply_4": return 4;
        }
        return -1;
    }

    /**
     * 判断该用户的角色是否包含rolename
     * @param username
     * @param rolename
     * @return
     */
    @Override
    public boolean isInCheckRole(String username,String rolename) {
        List<String> roleNames = userRoleMapper.getRoleByUserName(username);
        for(String item : roleNames)
            if(item.equals(rolename))
                return true;
        return false;
    }

    /**
     * 管理员审核单身公寓申请,要求不是最后一步审核
     *
     * @param step   当前审核的步骤
     * @param id
     * @param uid
     * @param result
     * @param note
     * @return
     */
    @Override
    public int checkApply(int step, String id, String uid, int result, String note) {
        if(step >= 4 || step <= 0)
            return -1;
        ZnzfNeedSingle entity = new ZnzfNeedSingle();
        entity.setId(id);
        entity.setCheckPeople(uid);
        entity.setCheckTime(new Date());
        entity.setOpinion(note);
        int tmp;
        if(result == 1)//审核意见通过
            entity.setStep(step + 1);
        else {
            entity.setCheckState(2);
        }
        tmp = znzfNeedSingleMapper.updateById(entity);
        if(tmp > 0){
            if(result == 1)//审核意见通过
                tmp = 1;
            else {
                tmp = 2;
            }
        }
        return tmp;
    }

    /**
     * 管理员审核单身公寓申请,最后一步审核
     *
     * @param step   当前审核的步骤
     * @param id
     * @param uid
     * @param result
     * @param note
     * @return
     */
    @Override
    public int checkApplyLastStep(int step, String id, String uid, int result, String note) {
        if(step != 4)
            return -1;
        ZnzfNeedSingle entity = new ZnzfNeedSingle();
        entity.setId(id);
        entity.setCheckPeople(uid);
        entity.setCheckTime(new Date());
        entity.setOpinion(note);
        int tmp;
        if(result == 1){//审核意见通过
            entity.setStep(step + 1);
            entity.setCheckState(0);
            if(znzfNeedSingleMapper.updateById(entity) <= 0)
                return -1;
            ZnzfNeedSingle apply = znzfNeedSingleMapper.selectById(id);
            return distribute(apply.getEid(),apply.getProjectId());//分配房源
        }
        //审核不通过
        entity.setCheckState(2);
        tmp = znzfNeedSingleMapper.updateById(entity);
        if(tmp > 0){
            if(result == 1)//审核意见通过
                tmp = 1;
            else {
                tmp = 2;
            }
        }
        return tmp;
    }

    @Override
    public ZnzfNeedSingle searchByEid(String eid) {
        LambdaQueryWrapper<ZnzfNeedSingle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnzfNeedSingle::getEid,eid);
        return znzfNeedSingleMapper.selectOne(queryWrapper);
    }

    @Override
    public int insert(ZnzfNeedSingle znzfNeedSingle) {
        LambdaQueryWrapper<ZnzfNeedSingle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnzfNeedSingle::getEid,znzfNeedSingle.getEid());
        ZnzfNeedSingle znzfNeedSingle1 =  znzfNeedSingleMapper.selectOne(queryWrapper);
        if(oConvertUtils.isNotEmpty(znzfNeedSingle1)){
            if(znzfNeedSingle1.getCheckState() == 1)
                return 0;
            znzfNeedSingleMapper.deleteById(znzfNeedSingle1);
        }
        znzfNeedSingleMapper.insert(znzfNeedSingle);
        return 1;
    }

    @Override
    public ZnzfNeedSingle searchByEidAndProjectId(String eid, String projectId) {
        LambdaQueryWrapper<ZnzfNeedSingle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnzfNeedSingle::getEid,eid);
        queryWrapper.eq(ZnzfNeedSingle::getProjectId,projectId);
        return znzfNeedSingleMapper.selectOne(queryWrapper);
    }
}
